import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;

public class StudentManagementSystem {
    private ArrayList<Student> students;
    private DefaultListModel<String> studentListModel;

    //构造器，自动创建学生对象
    public StudentManagementSystem() {
        students = new ArrayList<>();
        studentListModel = new DefaultListModel<>();
        loadStudents();
        createAndShowGUI();
    }

    //图形界面的创建，此方法被StudentManagementSystem构造器调用
    private void createAndShowGUI() {
        JFrame frame = new JFrame("学生管理系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1400, 300);
        frame.setLayout(new BorderLayout());

        JList<String> studentList = new JList<>(studentListModel);
        frame.add(new JScrollPane(studentList), BorderLayout.CENTER);

        JPanel panel = new JPanel();
        frame.add(panel, BorderLayout.SOUTH);

        //三个文本输入框和相应的标签
        JTextField nameField = new JTextField(10);
        JTextField classField = new JTextField(3);
        JTextField idField = new JTextField(10);
        JTextField gradesField = new JTextField(10);

        //panel.add(...) 将标签和文本框添加到一个面板 （panel） 上
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("班级:"));
        panel.add(classField);
        panel.add(new JLabel("学号:"));
        panel.add(idField);
        panel.add(new JLabel("成绩:"));
        panel.add(gradesField);

        JButton addButton = new JButton("添加学生");
        panel.add(addButton);

        JButton saveButton = new JButton("保存学生");
        panel.add(saveButton);

        JTextField deleteField = new JTextField(10);
        panel.add(deleteField);

        JButton deleteButton = new JButton("删除学生");
        panel.add(deleteButton);

        JTextField searchField = new JTextField(10);
        panel.add(searchField);

        JButton searchButton = new JButton("查询学生");
        panel.add(searchButton);

        JTextField modifyField = new JTextField(10);
        panel.add(modifyField);

        JButton modifyButton = new JButton("修改学生");
        panel.add(modifyButton);

        //用于为一个按钮（addButton）添加事件监听器（ActionListener）。当用户点击这个按钮时，会执行以下操作
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String class_ = classField.getText();
                String id = idField.getText();
                double grades = Double.parseDouble(gradesField.getText());
                Student student = new Student(name, class_, id, grades);
                students.add(student);
                studentListModel.addElement(student.toString());
                nameField.setText("");
                classField.setText("");
                idField.setText("");
                gradesField.setText("");
            }
        });

        modifyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String id = modifyField.getText();

                for (Student student : students) {
                    if (student.getId().equals(id)) {
                        student.setName(nameField.getText());
                        student.setClass_(classField.getText());
                        student.setGrades(Integer.parseInt(gradesField.getText()));
                        JOptionPane.showMessageDialog(frame, "学生信息已更新,请退出系统刷新界面");
                        return;
                    }
                }
            }
        });

        //用于为一个按钮（saveButton）添加事件监听器（ActionListener）。当用户点击这个按钮时，会执行以下操作
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //调用 saveStudents() 方法保存到文件中
                saveStudents();
                //JOptionPane.showMessageDialog(frame, "学生信息已保存!")  是 Java Swing 中用于显示消息对话框
                JOptionPane.showMessageDialog(frame, "学生信息已保存!");
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Iterator<Student> iterator = students.iterator();
                String deleteid = deleteField.getText();
                ObjectInputStream ois = null;
                try {
                    ois = new ObjectInputStream(new FileInputStream("students.dat"));
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                try {
                    students = (ArrayList<Student>) ois.readObject();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                }
                for (Student student : students) {
                    if (student.getId().equals(deleteid)) {
                        students.remove(student);
                        studentListModel.removeElement(student.toString());
                        nameField.setText("");
                        classField.setText("");
                        idField.setText("");
                        gradesField.setText("");
                    }
                }
            }
        });

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String searchid = searchField.getText();
                ObjectInputStream ois = null;
                try {
                    ois = new ObjectInputStream(new FileInputStream("students.dat"));
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                try {
                    students = (ArrayList<Student>) ois.readObject();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                }
                for (Student student : students) {
                    if (student.getId().equals(searchid)) {
                        JOptionPane.showMessageDialog(null, "找到学生: " + student.toString());
                    }
                }
            }
        });

        frame.setVisible(true);
    }

    //用于保存文本信息，在 saveButton 按钮时被调用，会保存到名为 students.dat 的文本在
    private void saveStudents() {
        //ObjectOutputStream 用于将 Java 对象转换为字节流
        //创建一个文件输出流，用于将数据写入名为 students.dat 的文件中
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students.dat"))) {
            oos.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //用于从 students.dat 的文件中加载学生数据
    private void loadStudents() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat"))) {
            //从ObjectInputStream 中读取一个对象，并将其强制转换为 ArrayList<Student> 类型
            students = (ArrayList<Student>) ois.readObject();
            //这是个增强for循环，用于循环遍历刚刚读取的学生列表中的每个 Student 对象
            for (Student student : students) {
                //将student对象的toString返回的字符串显示在界面（可以前往Student类中查看toString的实现）
                studentListModel.addElement(student.toString());
            }
        } catch (IOException | ClassNotFoundException e) {
            // 如果文件不存在或格式不对，忽略
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(StudentManagementSystem::new);

    }
}